// JavaScript Document
var Tween = {

    linear: function (t, b, c, d){
        return c*t/d + b;
    },
    easeIn: function(t, b, c, d){
        return c*(t/=d)*t + b;
    },
    easeOut: function(t, b, c, d){
        return -c *(t/=d)*(t-2) + b;
    },
    easeBoth: function(t, b, c, d){
        if ((t/=d/2) < 1) {
            return c/2*t*t + b;
        }
        return -c/2 * ((--t)*(t-2) - 1) + b;
    },
    easeInStrong: function(t, b, c, d){
        return c*(t/=d)*t*t*t + b;
    },
    easeOutStrong: function(t, b, c, d){
        return -c * ((t=t/d-1)*t*t*t - 1) + b;
    },
    easeBothStrong: function(t, b, c, d){
        if ((t/=d/2) < 1) {
            return c/2*t*t*t*t + b;
        }
        return -c/2 * ((t-=2)*t*t*t - 2) + b;
    },
    elasticIn: function(t, b, c, d, a, p){
        if (t === 0) {
            return b;
        }
        if ( (t /= d) == 1 ) {
            return b+c;
        }
        if (!p) {
            p=d*0.3;
        }
        if (!a || a < Math.abs(c)) {
            a = c;
            var s = p/4;
        } else {
            var s = p/(2*Math.PI) * Math.asin (c/a);
        }
        return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
    },
    elasticOut: function(t, b, c, d, a, p){
        if (t === 0) {
            return b;
        }
        if ( (t /= d) == 1 ) {
            return b+c;
        }
        if (!p) {
            p=d*0.3;
        }
        if (!a || a < Math.abs(c)) {
            a = c;
            var s = p / 4;
        } else {
            var s = p/(2*Math.PI) * Math.asin (c/a);
        }
        return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
    },
    elasticBoth: function(t, b, c, d, a, p){
        if (t === 0) {
            return b;
        }
        if ( (t /= d/2) == 2 ) {
            return b+c;
        }
        if (!p) {
            p = d*(0.3*1.5);
        }
        if ( !a || a < Math.abs(c) ) {
            a = c;
            var s = p/4;
        }
        else {
            var s = p/(2*Math.PI) * Math.asin (c/a);
        }
        if (t < 1) {
            return - 0.5*(a*Math.pow(2,10*(t-=1)) *
                Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
        }
        return a*Math.pow(2,-10*(t-=1)) *
            Math.sin( (t*d-s)*(2*Math.PI)/p )*0.5 + c + b;
    },
    backIn: function(t, b, c, d, s){
        if (typeof s == 'undefined') {
            s = 1.70158;
        }
        return c*(t/=d)*t*((s+1)*t - s) + b;
    },
    backOut: function(t, b, c, d, s){
        if (typeof s == 'undefined') {
            s = 3.70158;  //回缩的距离
        }
        return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
    },
    backBoth: function(t, b, c, d, s){
        if (typeof s == 'undefined') {
            s = 1.70158;
        }
        if ((t /= d/2 ) < 1) {
            return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
        }
        return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
    },
    bounceIn: function(t, b, c, d){
        return c - Tween['bounceOut'](d-t, 0, c, d) + b;
    },
    bounceOut: function(t, b, c, d){
        if ((t/=d) < (1/2.75)) {
            return c*(7.5625*t*t) + b;
        } else if (t < (2/2.75)) {
            return c*(7.5625*(t-=(1.5/2.75))*t + 0.75) + b;
        } else if (t < (2.5/2.75)) {
            return c*(7.5625*(t-=(2.25/2.75))*t + 0.9375) + b;
        }
        return c*(7.5625*(t-=(2.625/2.75))*t + 0.984375) + b;
    },
    bounceBoth: function(t, b, c, d){
        if (t < d/2) {
            return Tween['bounceIn'](t*2, 0, c, d) * 0.5 + b;
        }
        return Tween['bounceOut'](t*2-d, 0, c, d) * 0.5 + c*0.5 + b;
    }
};

var browser={
    versions:function(){
        var u = navigator.userAgent, app = navigator.appVersion;
        return {
            webKit: u.indexOf('AppleWebKit') > -1, //webKit内核
            trident: u.indexOf('Trident') > -1, //IE内核
            presto: u.indexOf('Presto') > -1, //opera内核
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
            //mobile: !!u.match(/AppleWebKit.*Mobile.*/)||!!u.match(/AppleWebKit/), //是否为移动终端
            mobile: !!u.match(/AppleWebKit.*Mobile/) || !!u.match(/Windows Phone/) || !!u.match(/Android/) || !!u.match(/MQQBrowser/),
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
            iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
            iPad: u.indexOf('iPad') > -1, //是否iPad
            webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
        };
    }()
};

function getHref(strName) {
    var strHref = document.location.href;
    var intPos = strHref.indexOf("?");
    var strRight = strHref.substr(intPos + 1);
    var arrTmp = strRight.split("&");
    for (var i = 0; i < arrTmp.length; i++) {
        var arrTemp = arrTmp[i].split("=");
        if (arrTemp[0].toUpperCase() == strName.toUpperCase()) return arrTemp[1];
    }
    return 0;
};

//选择器
function getEle(ele, oParent) {
    switch (ele.charAt(0)) {
        case "#":
            var objStr = ele.substring(1, ele.length);
            return document.getElementById(objStr);
            break;
        case ".":
            var sArg = ele;
            var reg = new RegExp("(^|\\s)" + sArg.substring(1) + "(\\s|$)"),
                arr = [],
                aEl = oParent || document.getElementsByTagName('*'),
                i;
            for (i = 0; i < aEl.length; i++) {
                reg.test(aEl[i].className) && arr.push(aEl[i]);
            }
            return arr;
            break;
        default :
            return (oParent || document).getElementsByTagName(ele);
            break;
    }
}

function getByClass(oParent,sClass){
    var aEle = (document||oParent).getElementsByTagName('*');
    var result = [];
    var re = new RegExp('\\b' + sClass + '\\b','i');

    for(var i=0;i<aEle.length;i++){
        if(re.test(aEle[i].className)){
            result.push(aEle[i]);
        }
    }
    return result;
}

function getStyle(obj, attr) {
    if(obj.currentStyle){
        return obj.currentStyle[attr];
    }else{
        return getComputedStyle(obj, false)[attr];
    };
}

function move(obj,json,times,fx,fn){
    var iCur = {};
    var startTime = now();
    for(var attr in json){
        iCur[attr] = 0;
        if(attr == 'opacity'){
            iCur[attr] = Math.round(getStyle(obj,attr)*100);
        }
        else{
            iCur[attr] = parseInt(getStyle(obj,attr));
        }
    }
    clearInterval(obj.timer);
    obj.timer = setInterval(function(){
        var changeTime = now();
        var scale = 1 -  Math.max(0,startTime  -  changeTime + times)/times ;
        for(var attr in json){
            var value = Tween[fx]( scale*times ,iCur[attr] , json[attr] - iCur[attr] , times );
            if(attr == 'opacity'){
                obj.style.filter = 'alpha(oapcity='+value+')';
                obj.style.opacity = value/100;
            }
            else{
                obj.style[attr] = value + 'px';
            }
        }
        if(scale == 1){
            clearInterval(obj.timer);
            if(fn){
                fn.call(obj);
            }
        }
    },13);
    function now(){
        return (new Date()).getTime();
    }
}

function getStyle(obj,attr){
    if(obj.currentStyle){
        return obj.currentStyle[attr];
    }
    else{
        return getComputedStyle(obj,false)[attr];
    }
}

function addEvent (obj, sEv, callBak) {
    obj.attachEvent ? obj.attachEvent("on" + sEv, callBak) : obj.addEventListener(sEv, callBak, false)
}

function removeEvent (obj, sEv, callBak) {
    obj.detachEvent ? obj.attachEvent("on" + sEv, callBak) : obj.removeEventListener(sEv, callBak, false)
}

//input处理
function delInputTxt(id){
    var obj = document.getElementById(id);
    var objVal = obj.value;
    addEvent(obj, 'focus', function (){
        if (obj.value == objVal) obj.value = '';
    });
    addEvent(obj, 'blur', function (){
        if (obj.value == '') obj.value = objVal;
    });
}

//检测设备
function checkDevice() {
    if (!browser.versions.mobile) {
        if (browser.versions.webKit || browser.versions.gecko) {
            getEle('#wrapper').style.width = '320px';
        } else {
            window.location.href = 'http://www.tage365.com';
        }
    }
}

function getViewSize () {
    var result = {};
    if (window.innerWidth) {
        result.winW = window.innerWidth;
        result.winH = window.innerHeight
    } else {
        if (document.documentElement.offsetWidth == document.documentElement.clientWidth) {
            result.winW = document.documentElement.offsetWidth;
            result.winH = document.documentElement.offsetHeight
        } else {
            result.winW = document.documentElement.clientWidth;
            result.winH = document.documentElement.clientHeight;
        }
    }
    result.docW = Math.max(document.documentElement.scrollWidth, document.body.scrollWidth, document.documentElement.offsetWidth);
    result.docH = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, document.documentElement.offsetHeight);
    return result;
}

function setCss (obj, json) {
    var arr = ["Webkit", "Moz", "O", "ms", ""];
    for (var attr in json) {
        if (attr.charAt(0) == "$") {
            for (var i = 0; i < arr.length; i++) {
                obj.style[arr[i] + attr.substring(1)] = json[attr]
            }
        } else {
            if (typeof json[attr] == "number") {
                switch (attr) {
                    case "opacity":
                        if (value < 0) value = 0;
                        obj.style.filter = "alpha(opacity:" + value + ")";
                        obj.style.opacity = value / 100;
                        break;
                    case "zIndex":
                        obj.style[attr] = json[attr];
                        break;
                    default:
                        obj.style[attr] = json[attr] + "px";
                }
            } else {
                if (typeof json[attr] == "string") obj.style[attr] = json[attr];
            }
        }
    }
}

function addClass(obj,className){
    if(obj&&obj.nodeType&&obj.nodeType===1&&className&&typeof className=='string'){
        var reg=new RegExp('\\b'+className+'\\b');
        if(!reg.test(obj.className)){
            obj.className+=" "+className;
        }
    }
}

function removeClass(ele,className){
    if(ele&&ele.nodeType&&ele.nodeType===1&&className&&typeof className=='string'){
        var reg=new RegExp('\\b'+className+'\\b','g');
        ele.className=ele.className.replace(reg,'');
    }
}

addEvent(window, 'load', function(){
    //检测设备
    checkDevice();

    //返回顶部
    if(getEle('.toTop')[0]){
        getEle('.toTop')[0].onclick = function (){
            var timer = setInterval(function (){
                var sct = document.documentElement.scrollTop || document.body.scrollTop;
                if(document.documentElement.scrollTop){
                    document.documentElement.scrollTop = sct + -sct/20;
                }else{
                    document.body.scrollTop = sct + -sct/20;
                }
                if(!sct) clearInterval(timer);
            },10)
        };
    }
});

function TGSlider (opts){
    var iNow = 0,
        iNow_new = iNow,
        oSlider = getEle(opts.dom.id),
        oSliderList = getEle(opts.dom.list)[0],
        oSliderAll = oSliderList.getElementsByTagName('ul')[0],
        oSliderPrev = oSlider.getElementsByClassName('sliderPrev')[0],
        oSliderNext = oSlider.getElementsByClassName('sliderNext')[0],
        aSliderNum = getEle(opts.dom.num)[0].getElementsByTagName('a'),
        aItem = oSliderAll.getElementsByTagName('li'),
        iItemWidth = aItem[0].offsetWidth,
        iItemHeight = aItem[0].offsetHeight,
        iWinWidth = getEle('#wrapper').offsetWidth,
        iLen = aItem.length,
        startX = 0,
        endX = 0,
        iRange = 30,
        iDelay = 5000,
        timer;

    init = function (){
        if(iLen <= 1) return;
        iWinWidth = getEle('#wrapper').offsetWidth;
        addClass(aSliderNum[0], 'curr');
        setCss(oSlider, {width: iWinWidth});
        for(var i=0; i<iLen; i++){
            setCss(aItem[i], {
                width: iWinWidth,
                zIndex:10 - i,
                height: iItemHeight,
                position:'absolute',
                left:!i ? 0 : iWinWidth,
                top:0,
                display : iNow == i || iNow_new == i ? 'block' : 'none'
            })
        }
        setCss(oSliderList, {
            width: iWinWidth,
            height: iItemHeight,
            overflow: 'hidden',
            position: 'relative'
        });
        setCss(oSliderAll, {
            width: iWinWidth*2,
            height: iItemHeight,
            position:'absolute',
            left:0,
            top:0
        });
        for(var i=0; i<iLen; i++){
            aSliderNum[i].index = i;
            (function (i){
                addEvent(aSliderNum[i], opts.event, function (){
                    iNow = iNow_new;
                    iNow_new = i;
                    render();
                })
            })(i)
        }
        addEvent(oSliderPrev, 'click', function(){
            iNow = iNow_new;
            iNow_new--;
            if(iNow_new == -1){
                console.log(1)
                iNow_new = iLen - 1;
            };
            render();
        });
        addEvent(oSliderNext, 'click', function(){
            iNow = iNow_new;
            iNow_new++;
            if(iNow_new == iLen){
                iNow_new = 0;
            };
            render();
        });
        //addEvent(oSlider, 'mouseover', function (){clearInterval(timer)});
        //addEvent(oSlider, 'mouseout', function (){autoPlay()});
    },

        render = function () {
            for(var i=0; i<iLen; i++){
                if(i == iNow_new){
                    setCss(aItem[i], {
                        left:iNow_new > iNow ? iWinWidth : -iWinWidth,
                        display:'block'
                    });
                    addClass(aSliderNum[i], 'curr');
                }else{
                    removeClass(aSliderNum[i], 'curr');
                }
            }
            move(aItem[iNow_new],{
                left: 0
            },1000,'easeBothStrong');
            move(aItem[iNow],{
                left: iNow_new > iNow ? -iWinWidth : iWinWidth
            },1000,'easeBothStrong');
        },

        autoPlay = function (){
            timer = setInterval(function (){
                iNow = iNow_new;
                if(iNow_new == iLen-1){
                    iNow_new = 0;
                }else{
                    iNow_new++;
                }
                render();
            }, iDelay)
        },

        isTouchDevice = function () {
            try {
                document.createEvent("TouchEvent");
                oSlider.addEventListener('touchstart', touchSatrtFunc, false);
                oSlider.addEventListener('touchmove', touchMoveFunc, false);
                oSlider.addEventListener('touchend', touchEndFunc, false);



            }
            catch (e) {}
        },

        touchSatrtFunc = function (e) {
            try {
                var touch = e.touches[0];
                startX = Number(touch.pageX);
            }
            catch (e) {
                alert('touchSatrtFunc：' + e.message);
            }
        },

        touchMoveFunc = function (e) {
            try {
                e.preventDefault();
                var touch = e.touches[0];
                endX =  Number(touch.pageX);
            }
            catch (e) {
                alert('touchMoveFunc：' + e.message);
            }
        },

        touchEndFunc = function (e) {
            try {
                e.preventDefault();
                //alert(startX + '__' + endX)
                if(!endX) {
                    return false;
                }else{
                    iNow = iNow_new;
                    if (endX - startX >= iRange) {
                        iNow_new--;
                        if(iNow_new == -1){
                            iNow_new = iLen-1;
                        }
                        render();
                    }
                    if (endX - startX <= -iRange) {
                        iNow_new++;
                        if(iNow_new == iLen){
                            iNow_new = 0;
                        }
                        render();
                    }
                    endX = startX = 0;
                }
            }
            catch (e) {
                alert('touchEndFunc：' + e.message);
            }
        };
    init();
    //autoPlay();
    //isTouchDevice();

}

